from flask import request, make_response, send_from_directory
from app.utils import spatial_enhancement, point_enhancement, frequency_enhancement
import os
from app import app


current_dir = os.path.dirname(os.path.abspath(__file__))


@app.route("/")
def index():
    return send_from_directory(app.static_folder, "index.html")


@app.route("/<path:path>")
def static_files(path):
    return send_from_directory(app.static_folder, path)


# 空间锐化滤波器算法
@app.route("/process_spatial", methods=["POST"])
def process_spatial():
    if "image" not in request.files:
        return "No image part", 400
    file = request.files["image"]
    if file.filename == "":
        return "No selected file", 400
    img_stream = request.files["image"].stream
    config = request.form.get("config")
    config = eval(config)
    if config["type"] == "1":
        print("laplacian_sharpening")
        processed_image_data = spatial_enhancement.laplacian_sharpening(img_stream)
    elif config["type"] == "2":
        print("sobel_edge_detection")
        processed_image_data = spatial_enhancement.sobel_edge_detection(img_stream)
    else:
        print("combine_sharpening")
        processed_image_data = spatial_enhancement.combine_sharpening(img_stream)
    response = make_response(processed_image_data)
    return response


# 点运算图像增强
@app.route("/process_point", methods=["POST"])
def process_point():
    if "image" not in request.files:
        return "No image part", 400
    file = request.files["image"]
    if file.filename == "":
        return "No selected file", 400
    img_stream = request.files["image"].stream
    config = request.form.get("config")
    config = eval(config)
    if config["type"] == 1:
        # 将img_stream保存到文件中
        print("enhance_input_image")
        with open(
            current_dir + "/utils/test1/input.jpg",
            "wb",
        ) as f:
            f.write(img_stream.read())
        processed_image_data = point_enhancement.enhance_input_image(
            current_dir + "/utils/test1/input.jpg"
        )
    else:
        # 将img_stream保存到文件中
        print("enhance_brightness_and_sharpen")
        with open(current_dir + "/utils/test1/input.jpg", "wb") as f:
            f.write(img_stream.read())
        processed_image_data = point_enhancement.enhance_brightness_and_sharpen(
            current_dir + "/utils/test1/input.jpg", current_dir + "/utils/test1/output"
        )
    response = make_response(processed_image_data)
    return response


# 频域图像增强
@app.route("/process_frequency", methods=["POST"])
def process_frequency():
    if "image" not in request.files:
        return "No image part", 400
    file = request.files["image"]
    if file.filename == "":
        return "No selected file", 400
    img_stream = request.files["image"].stream
    processed_image_data = frequency_enhancement.gauss_filter(img_stream)
    response = make_response(processed_image_data)
    return response
